package com.lglbc.day6.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Description TODO
 * @Author 乐哥聊编程
 * @Date 2022/12/10 10:00
 */
@Slf4j
public class NettyMsgDecoder extends ByteToMessageDecoder {
    int length=0;
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes()>4){
            if(length==0){
                length=in.readInt();
            }
            if(in.readableBytes()<length){
                log.info("长度不够，继续等待");
                return;
            }
            byte[] content=new byte[length];
            in.readBytes(content);
            NettyMsg message=new NettyMsg();
            message.setLen(length);
            message.setContent(content);
            // 发送给下一个handler
            out.add(message);
            length=0;
        }
    }
}
